package com.wzy.business.base.photo

import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.wangzhenyu.common.design.MySingleton
import com.wangzhenyu.common.netcore.networking.http.core.PassThroughExecutor
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.net.URLDecoder
import java.util.concurrent.TimeUnit

class CommonRepository private constructor() {


    companion object : MySingleton<String, CommonRepository>() {

        private const val baseUrl = "http://image.kypeople.cn/api/v1/"

        override val creator: (String) -> CommonRepository
            get() = {
                initRetrofit()
                initInterceptor()
                CommonRepository()
            }

        private fun initRetrofit() {

            initOkHttpClient()

            retrofit = okHttpClient?.let {
                Retrofit.Builder()
                    .baseUrl(baseUrl)
                    //在nextRequestBodyConverter(...) 方法 和 nextResponseBodyConvert(...)方法在,可以看到:
                    //按照retrofit的逻辑，是从前往后进行匹配，如果匹配上，就忽略后面的，直接使用。
                    .addConverterFactory(GsonConverterFactory.create())
                    .callbackExecutor(PassThroughExecutor())
                    .client(it)
                    .build()
            }
        }

        private fun initOkHttpClient() {

            val logging = HttpLoggingInterceptor { message ->
                try {
                    val text = URLDecoder.decode(message, "utf-8")
                    LogUtils.d(text)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            logging.setLevel(HttpLoggingInterceptor.Level.BODY)

            val httpClientBuilder = OkHttpClient.Builder()
            httpClientBuilder.connectTimeout(90L, TimeUnit.SECONDS)
            httpClientBuilder.readTimeout(90L, TimeUnit.SECONDS)

            interceptor?.let { httpClientBuilder.addInterceptor(it) }
            if (AppUtils.isAppDebug()) {
                httpClientBuilder.addInterceptor(logging)
            }
            okHttpClient = httpClientBuilder.build()
        }

        private fun initInterceptor() {
            interceptor = Interceptor { chain ->
                val loginInfo = DuckManager.getDuckLoginInfo()
                //获取原始的originalRequest
                val request = chain.request()
                //获取originalRequest的创建者builder
                val newBuilder = request.newBuilder()
                if (DuckManager.isLogin() && loginInfo != null) {
                    //添加Authorization
                    newBuilder.addHeader("Authorization", loginInfo.data?.token ?: "")
                }
                val newRequest = newBuilder.build()
                val response: Response = try {
                    chain.proceed(newRequest)
                } catch (e: Exception) {
                    throw e
                }
                response
            }
        }

        @Volatile
        private var retrofit: Retrofit? = null

        @Volatile
        private var okHttpClient: OkHttpClient? = null

        @Volatile
        private var interceptor: Interceptor? = null

        suspend fun uploadFile(file: File?, isImage: Boolean = true) {

            if (file == null) return
            //处理图片
            var imageType = "image/png"
            if (file.name.endsWith("jpg")) {
                imageType = "image/jpg"
            } else if (file.name.endsWith("jpeg")) {
                imageType = "image/jpeg"
            }

            var imageFile = file

            if (isImage)
            {
//                imageFile = if (file.name.endsWith("png")) {
//                    //Compressor.
//                }
            }


        }

    }


    fun getRetrofit() = retrofit


}


